// 选择反应盘弹层
import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import { Modal, Form, Input, message } from "antd";

import _ from "lodash";

import {
  createList,
  ROWWORD,
  BASEWIDE,
  BASEHEIGHT,
  RATE,
  MARGIN,
  ReactionSlotName,
} from "../../utils";

import StepTop from "./StepTop";
import ShelfMiniPlane from "./ShelfMiniPlane";

// import ReacterPlateCanvas from "./ReacterPlateCanvas";

import { ITStore } from "../../store";

import { ITShelf, ITBottle, ITDesinger } from "../../store/interfaces";

import "../Workbench/index.less";

interface TProp {
  store: ITStore;
  isShow: boolean;
  close: () => void;
  onSelect: (data: any) => void;
}

interface ITShelfBottle {
  shelfInfo?: ITShelf | null;
  bottleInfo?: ITBottle | null;
}

const DesignerWorkbenchPannel: FC<TProp | any> = inject("store")(
  observer(({ store, onSelect }: TProp) => {
    const {
      languageStore: { lang, langCur },
      designerStore: {
        updateDesigner,
        currentDesigner,
        changeCurrentWorkbench,
        currentWorkbench,
        currentSlotInfo,
        currentReactorSlotInfo,
      },
      workbenchStore: { getWorkbenchById },
      shelfStore: { allShelf },
      bottleStore: { allBottle },
    } = store;

    const [rowList, setRowList] = useState<number[]>([]);

    const [columnList, setColumnList] = useState<number[]>([]);

    const [slotHeight, setSlotHeight] = useState<number>(0);

    const [slotWide, setSlotWide] = useState<number>(0);

    const [slotMargin, setSlotMargin] = useState<number>(0);

    const [slotShelf, setSlotShelf] = useState<any>(null);

    const [reactorSlotShelf, setReactorSlotShelf] = useState<any>(null);

    const [selectedslotName, setSelectedslotName] = useState("");

    useEffect(() => {
      setSlotHeight(BASEHEIGHT * RATE);
      setSlotWide(BASEWIDE * RATE);
      setSlotMargin(MARGIN * RATE);
    }, []);

    useEffect(() => {
      setSlotShelf(currentSlotInfo);
      setReactorSlotShelf(currentReactorSlotInfo);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentSlotInfo, currentReactorSlotInfo]);

    useEffect(() => {
      const getWorkbench = async (data: any) => {
        const result: any = await getWorkbenchById(data);
        changeCurrentWorkbench(result);
      };

      if (currentDesigner && !currentWorkbench?.id) {
        const { workbench } = currentDesigner;
        getWorkbench({ id: workbench });
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentDesigner]);

    useEffect(() => {
      if (currentWorkbench) {
        const { row, column } = currentWorkbench;
        setRowList(createList(row || 0));
        setColumnList(createList(column || 0));
      }
    }, [currentWorkbench]);

    const getBottleInfoById = (id: string): ITBottle | null => {
      let temp = null;
      allBottle.some((item) => {
        if (item.id === id) {
          temp = item;
          return true;
        }
        return false;
      });
      return temp;
    };

    const getShelfAndBottleInfo = (name: string): ITShelfBottle => {
      let temp = null;
      let tempBottle = null;
      allShelf.some((item) => {
        if (item.name === name) {
          temp = item;
          return true;
        }
        return false;
      });
      if (temp) {
        const { bottleType } = temp;
        tempBottle = getBottleInfoById(bottleType);
      }
      return {
        shelfInfo: temp,
        bottleInfo: tempBottle,
      };
    };

    const slotClick = (slotname: string) => {
      setSelectedslotName(slotname);
      onSelect(slotname);
    };

    // 判断盘是否有试剂
    const getReagentStatusBySlotName = (slot: string) => {
      let hasReagent = false;
      if (currentDesigner) {
        const { reagents } = currentDesigner;
        if (reagents && reagents[slot] && !_.isEmpty(reagents[slot])) {
          hasReagent = true;
        }
      }
      return hasReagent;
    };

    return (
      <div className="workbenchplane">
        <div
          className="bord"
          style={{
            paddingLeft: slotMargin,
            paddingTop: slotMargin,
          }}
        >
          {rowList.map((rowItem) => {
            return (
              <div
                className="row"
                key={rowItem}
                style={{
                  marginBottom: slotMargin,
                  height: slotHeight,
                }}
              >
                {columnList.map((colItem) => {
                  const slotName = `${ROWWORD[rowItem]}${colItem + 1}`;
                //   const isC3 = slotName === ReactionSlotName;

                  let hasMiniPlane = false;
                  let ShelfMiniPlaneParam: ITShelfBottle = {};
                  let shelfType;
                  // let shelfName = null;
                  if (slotShelf) {
                    let slotshelfInfo = slotShelf[slotName];
                    if (slotshelfInfo) {
                      hasMiniPlane = true;
                      const { shelf } = slotshelfInfo;
                      // shelfName = shelf;
                      ShelfMiniPlaneParam = getShelfAndBottleInfo(shelf);
                      const { shelfInfo } = ShelfMiniPlaneParam;
                      shelfType = shelfInfo?.rackType;
                    }
                  }

                  let display =
                    shelfType === "trash" ||
                    shelfType === "tiprack" ||
                    shelfType === "cap" ||
                    !shelfType ||
                    getReagentStatusBySlotName(slotName);

                  return (
                    <div
                      className={`slot designer ${display ? "display" : ""} ${
                        selectedslotName === slotName ? "selected" : ""
                      }`}
                      style={{
                        width: slotWide,
                        height: slotHeight,
                        marginRight: slotMargin,
                      }}
                      key={colItem}
                      onClick={() => {
                        !display && slotClick(slotName);
                      }}
                    >
                      {!hasMiniPlane && (
                        <div className="slotlabel">{slotName}</div>
                      )}
                      {hasMiniPlane && (
                        <ShelfMiniPlane
                          {...ShelfMiniPlaneParam}
                          slotName={slotName}
                        />
                      )}
                    </div>
                  );
                })}
              </div>
            );
          })}
        </div>
      </div>
    );
  })
);

const SelectReactorPlateModal: FC<TProp | any> = ({
  store,
  isShow,
  close,
}: TProp): JSX.Element => {
  const {
    languageStore: { lang },
    designerStore: {
      currentDesigner,
      getDesignerInfo,
      updateDesigner,
      createReactDesigner,
      getReactDesignerList,
      updateReactDesigner,
    },
  } = store;
  const [form] = Form.useForm();

  const [selectReactionPlate, setSelectReactionPlate] = useState("");

  const [addEditLoading, setAddEditLoading] = useState(false);

  const closeModal = () => {
    close();
  };

//   const createReactionReagents = () => {
//     const { reagents } = currentDesigner as ITDesinger;
//     const reagentIdSets = new Set();
//     if (reagents) {
//       const plateValues = Object.values(reagents);
//       if (plateValues.length) {
//         plateValues.forEach((plateValue: any) => {
//           const slotValues = Object.values(plateValue);
//           if (slotValues.length) {
//             slotValues.forEach((slotValue: any) => {
//               reagentIdSets.add(slotValue.reagentId);
//               // const reagentInfo = getReagentInfoById(slotValue.reagentId);
//             });
//           }
//         });
//       }
//     }
//     return Array.from(reagentIdSets);
//   };

  const onFinish = async (values: any) => {
    if (!selectReactionPlate) {
      message.error(lang["langselectreactionslot"]);
    }

    const { name } = values;
    setAddEditLoading(true);
    const reactionres: any = await createReactDesigner({
      name,
      plate: selectReactionPlate,
      designer: currentDesigner?.id,
    });

    // 这里创建默认的实验试剂
    // const reagentsort = createReactionReagents();
    const res = await updateReactDesigner({
      id: reactionres.id,
      reagentsort:[],
    });

    setAddEditLoading(false);
    if (!res) {
      message.success(lang["langaddsuccess"]);
      closeModal();
      getReactDesignerList({
        designer: currentDesigner?.id,
      });
    }
    form.resetFields();
    setSelectReactionPlate("");
  };

  return (
    <Modal
      title={lang["langprotocoldesigner"]}
      open={isShow}
      onOk={form.submit}
      onCancel={closeModal}
      destroyOnClose={true}
      //   footer={null}
      width={1170}
      className="chemdesignermodal"
      confirmLoading={addEditLoading}
    >
      <Form
        name="designerForm"
        form={form}
        // labelCol={{ span: 6 }}
        // wrapperCol={{ span: 18 }}
        onFinish={onFinish}
      >
        <Form.Item
          label={lang["langreactionname"]}
          name="name"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
      </Form>
      <div className="selectreactorplate">
        {lang["langselectreactionslot"]}：
      </div>
      <DesignerWorkbenchPannel
        close={closeModal}
        onSelect={setSelectReactionPlate}
      />
    </Modal>
  );
};

export default inject("store")(observer(SelectReactorPlateModal));
